This tutorial shows how to extract your Custom Shape into separate struct which can then be used as built in Shapes.
Extract into struct (With absolute coordinates)
struct ContentView : View {
var body : some View {
MyTriangle()
.stroke(Color.green, lineWidth: 5)
}
}
struct MyTriangle : Shape {
func path(in rect: CGRect) -> Path {
Path { path in
path.move (to: CGPoint(x: 200, y: 200))
path.addLine(to: CGPoint(x: 400, y: 200))
path.addLine(to: CGPoint(x: 300, y: 300))
path.closeSubpath()
}
}
}
We will now rewrite our code so that it doesn't use absolute coordinates.
Instead we want our triangle to take up the whole surface so that we could later adjust he size using .frame().
rect is invisible scratchpad inside which we can draw our triangle and which can get transformed by .frame().
Remove absolute coordinates
struct ContentView : View {
var body : some View {
MySquare()
.stroke(Color.green, lineWidth: 5)
.frame(width: 250, height: 250)
}
}
struct MySquare: Shape {
func path(in rect: CGRect) -> Path {
Path { path in
path.move (to: CGPoint(x: 0, y: 0))
path.addLine(to: CGPoint(x: rect.size.width, y: 0))
path.addLine(to: CGPoint(x: rect.size.width / 2, y: rect.size.height))
path.closeSubpath()
}
}
}
With absolute coordinates Removed absolute coordinates